package com.example.zhanglinan.vrdemo.activity;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;


import com.example.zhanglinan.vrdemo.R;
import com.google.vr.sdk.widgets.video.VrVideoEventListener;
import com.google.vr.sdk.widgets.video.VrVideoView;

import java.io.IOException;


public class VideoPlayerActivity extends AppCompatActivity {

    private VrVideoView vrVideoView;
    private SeekBar seekBar;
    private TextView tvVrVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_palyer);
        String play = getIntent().getStringExtra("play");

        vrVideoView = (VrVideoView) findViewById(R.id.vr_video);
        seekBar = (SeekBar) findViewById(R.id.seekbar_vr_video);
        tvVrVideo = (TextView) findViewById(R.id.tv_vr_video);
        vrVideoView.setEventListener(new VrVideoEventListener() {
            @Override
            public void onLoadSuccess() {
                super.onLoadSuccess();
                seekBar.setMax((int) vrVideoView.getDuration());
            }

            @Override
            public void onLoadError(String errorMessage) {
                super.onLoadError(errorMessage);
                Toast.makeText(VideoPlayerActivity.this, "视频加载异常。。。", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onClick() {
                super.onClick();
            }

            @Override
            public void onNewFrame() {
                super.onNewFrame();
                seekBar.setProgress((int) vrVideoView.getCurrentPosition());
                tvVrVideo.setText("当前进度:" + String.format("%.2f", vrVideoView.getCurrentPosition() / 1000f));
            }
        });
        new VideoTask().execute(play);
    }

    class VideoTask extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... params) {
            String url = params[0];
            VrVideoView.Options options = new VrVideoView.Options();
            options.inputType = VrVideoView.Options.TYPE_MONO;
            options.inputFormat = VrVideoView.Options.FORMAT_DEFAULT;
            try {
                vrVideoView.loadVideo(Uri.parse(url), options);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        vrVideoView.resumeRendering();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vrVideoView.pauseRendering();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vrVideoView.shutdown();
    }
}
